package com.test.esfiledemo.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class ESConfig {


    @Value("${es.nodes}")
    private String nodes;

    @Value("${es.user}")
    private String user;

    @Value("${es.password}")
    private String password;

    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        COMMON_OPTIONS = builder.build();
    }


    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestClientBuilder builder = RestClient.builder(init(nodes));
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
        builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
        RestHighLevelClient restClient = new RestHighLevelClient(builder);
        return restClient;
    }


    private HttpHost[] init(String list) {
        List<HttpHost> result = new ArrayList<>();
        if (list.indexOf(",") == -1) {
            String[] hostPort = list.split(":");
            HttpHost httpHost = new HttpHost(hostPort[0], Integer.parseInt(hostPort[1]), HttpHost.DEFAULT_SCHEME_NAME);
            result.add(httpHost);
        } else {
            String[] hosts = list.split(",");
            for (int i = 0; i < hosts.length; i++) {
                String[] hostPort = hosts[i].split(":");
                HttpHost httpHost = new HttpHost(hostPort[0], Integer.parseInt(hostPort[1]), HttpHost.DEFAULT_SCHEME_NAME);
                result.add(httpHost);
            }
        }

        HttpHost[] arr = new HttpHost[result.size()];
        for (int i = 0; i < result.size(); i++) {
            arr[i] = result.get(i);
        }
        return arr;
    }


}
